//
//  RYNongchangListVM.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/18.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import Foundation
import UIKit
import RxSwift
import Moya
import Alamofire
import HandyJSON

class RYNongchangListVM: NSObject {
    
    func baseRequest<T: HandyJSON>(disposeBag: DisposeBag,type: SYApiManager, modelClass: T.Type, noHud: Bool = false, noJiance: Bool = false ,notishi: Bool = false, Success:@escaping (T)->(), Error: @escaping ()->()) {
        DispatchQueue.main.async {
            if !noHud {
                HUDUtil.showHud()
            }
        }
//        UserDefaults.standard.value(forKey: type.path + UserInstance.userId!)
        ApiManagerProvider.rx.request(type)
            .asObservable()
            .mapHandyJsonModel(type.path, modelClass)
            .subscribe { (event) in
                
                switch event {
                case let .next(data):
//                    let dic: Dictionary = UserDefaults.standard.value(forKey: type.path + UserInstance.userId! + REQUEST_DIC) as? Dictionary ?? [:]
                    let dic: Dictionary = UserDefaults.standard.value(forKey: type.path + REQUEST_DIC) as? Dictionary ?? [:]
                    let code: String = (dic["code"] as? String) ?? ""
                    let message: String = (dic["message"] as? String) ?? ""
                    
                    if code == "10000" {
                        DispatchQueue.main.async {
                            HUDUtil.hideHud()
                        }
                        Success(data)
                    } else {
                        DispatchQueue.main.async {
                            if code == "10001" {//"session失效！"
                                DispatchQueue.main.async {
                                    HUDUtil.hideHud()
                                }
                                if !noJiance {
//                                    SYTokenCheck.toLoginVC()
                                }
                            } else {
                                if notishi == false {
                                    HUDUtil.showBlackTextView(text: message, detailText:"", delay: 1.5) {
                                        
                                    }
                                }
                                
                            }
                        }
                        
                        log.info(message)
                        Error()
                        break
                    }
                    
                    break
                case let .error(error):
                    DispatchQueue.main.async {
                        
                        HUDUtil.showBlackTextView(text: error.localizedDescription, detailText:"", delay: 1.5) {
                            
                        }
                        
                        
                    }
                    log.info(error)
                    Error()
                    break
                default:
                    break
                }
            }.disposed(by: disposeBag)
        
    }
    
    func cancel(type: SYApiManager) {
        
    }
    
}

import XCGLogger

let XCCacheDirectory: URL = {
    let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
    return urls[urls.endIndex - 1]
}()

let log: XCGLogger = {
    // Setup XCGLogger
    let log = XCGLogger.default
    
    #if USE_NSLOG // Set via Build Settings, under Other Swift Flags
        log.remove(destinationWithIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier)
        log.add(destination: AppleSystemLogDestination(identifier: XCGLogger.Constants.systemLogDestinationIdentifier))
        log.logAppDetails()
    #else
        let logPath: URL = XCCacheDirectory.appendingPathComponent("XCGLogger_Log.txt")
        log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath)
        
        // Add colour (using the ANSI format) to our file log, you can see the colour when `cat`ing or `tail`ing the file in Terminal on macOS
        // This is mostly useful when testing in the simulator, or if you have the app sending you log files remotely
        if let fileDestination: FileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination {
            let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter()
            ansiColorLogFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint])
            ansiColorLogFormatter.colorize(level: .debug, with: .black)
            ansiColorLogFormatter.colorize(level: .info, with: .blue, options: [.underline])
            ansiColorLogFormatter.colorize(level: .warning, with: .red, options: [.faint])
            ansiColorLogFormatter.colorize(level: .error, with: .red, options: [.bold])
            ansiColorLogFormatter.colorize(level: .severe, with: .white, on: .red)
            fileDestination.formatters = [ansiColorLogFormatter]
        }
        
        // Add colour to the console destination.
        // - Note: You need the XcodeColors Plug-in https://github.com/robbiehanson/XcodeColors installed in Xcode
        // - to see colours in the Xcode console. Plug-ins have been disabled in Xcode 8, so offically you can not see
        // - coloured logs in Xcode 8.
        //if let consoleDestination: ConsoleDestination = log.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination {
        //    let xcodeColorsLogFormatter: XcodeColorsLogFormatter = XcodeColorsLogFormatter()
        //    xcodeColorsLogFormatter.colorize(level: .verbose, with: .lightGrey)
        //    xcodeColorsLogFormatter.colorize(level: .debug, with: .darkGrey)
        //    xcodeColorsLogFormatter.colorize(level: .info, with: .blue)
        //    xcodeColorsLogFormatter.colorize(level: .warning, with: .orange)
        //    xcodeColorsLogFormatter.colorize(level: .error, with: .red)
        //    xcodeColorsLogFormatter.colorize(level: .severe, with: .white, on: .red)
        //    consoleDestination.formatters = [xcodeColorsLogFormatter]
        //}
    #endif
    
    // You can also change the labels for each log level, most useful for alternate languages, French, German etc, but Emoji's are more fun
    //    log.levelDescriptions[.verbose] = "🗯"
    //    log.levelDescriptions[.debug] = "🔹"
    //    log.levelDescriptions[.info] = "ℹ️"
    //    log.levelDescriptions[.warning] = "⚠️"
    //    log.levelDescriptions[.error] = "‼️"
    //    log.levelDescriptions[.severe] = "💣"
    // Alternatively, you can use emoji to highlight log levels (you probably just want to use one of these methods at a time).
    let emojiLogFormatter = PrePostFixLogFormatter()
    emojiLogFormatter.apply(prefix: "🗯🗯🗯 ", postfix: " 🗯🗯🗯", to: .verbose)
    emojiLogFormatter.apply(prefix: "🔹🔹🔹 ", postfix: " 🔹🔹🔹", to: .debug)
    emojiLogFormatter.apply(prefix: "👉👉👉 ", postfix: " 👈👈👈", to: .info)
    emojiLogFormatter.apply(prefix: "⚠️⚠️⚠️ ", postfix: " ⚠️⚠️⚠️", to: .warning)
    emojiLogFormatter.apply(prefix: "‼️‼️‼️ ", postfix: " ‼️‼️‼️", to: .error)
    emojiLogFormatter.apply(prefix: "💣💣💣 ", postfix: " 💣💣💣", to: .severe)
    log.formatters = [emojiLogFormatter]
    
    return log
}()




struct SGBaseModel<T: HandyJSON>: HandyJSON {
    
    var status: String?
    var code: Int?
    var message: String?
    var date: String?
    var token: String?
    var data: T?

}

struct SGBaseNoPageListModel<T: HandyJSON>: HandyJSON {
    
    var status: String?
    var code: Int?
    var message: String?
    var date: String?
    var data: [T]?

}

struct SGBaseListModel<T: HandyJSON>: HandyJSON {
    
    var status: String?
    var code: Int?
    var message: String?
    var date: String?
    var data: SGPagerModel<T>?

}

struct SGPayModel: HandyJSON {
    
    var status: String?
    var code: Int?
    var message: String?
    var date: String?
    var token: String?
    var data: String?

}

struct SGPagerModel<T: HandyJSON>: HandyJSON {

    var size: Int?
    var current: Int?
    var pages: Int?
    var total: Int?
    var records: [T]?
}

struct SGPagerTestModel: HandyJSON, Equatable
{
    var test: String?
    var id: Int = 0
}


struct SGSimpleModel: HandyJSON, Equatable
{
    
    var id: String?
}
